<?php
if (!defined('CMS')) die;
global$Eleanor, $head;
$Eleanor->mconfig = include($Eleanor->module['path'] . 'config.php');
Eleanor::$Language->Load($Eleanor->module['path'] . 'lang_user-*.php', $Eleanor->mconfig['n']);
Eleanor::LoadOptions($Eleanor->mconfig['opts']);
Eleanor::$Template->queue[] = $Eleanor->mconfig['usertpl'];

$curls = array();
$adver = NULL;
if($Eleanor->Url->is_static) {
	$adver=false;
	$str=$Eleanor->Url->GetEnding(array($Eleanor->Url->ending,$Eleanor->Url->delimiter),true);
	$_GET+=$Eleanor->Url->Parse($str ? array() : array('do'));
	if($str)
	{
		$curls=isset($_GET['']) ? (array)$_GET[''] : array();
		if($str==$Eleanor->Url->ending and !isset($_GET['page']))
			$adver=array_pop($curls);
	}
}
$cid = isset($_GET['cid']) ? (int) $_GET['cid'] : 0;
$nid = isset($_GET['nid']) ? (int) $_GET['nid'] : 0;

$Eleanor->Categories->Init($Eleanor->mconfig['c']);
if (isset($_GET['do'])) {
	$d = (string)$_GET['do'];
	switch ($d) {
		case'cr':
			cr();
		break;
		case'my':
			if (Eleanor::$Login->IsUser())
				MyAdver();
			else
				AdverBeginPage() . AddEditAdver(false, null, true);
		break;
		case'add':
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && Eleanor::$our_query)
				SaveAdver(false);
			else
				AddEditAdver(false);
		break;
//		case'edit':
//		case'delete':
//			if ($Eleanor->Url->is_static)
//				$id = (isset($_GET['']) && is_array($_GET[''])) ? reset($_GET['']) : false;
//			else
//				$id = isset($_GET['id']) ? (string) $_GET['id'] : false;
//			if (Eleanor::$Login->IsUser())
//			switch ($d) {
//				case'edit':
//					if ($_SERVER['REQUEST_METHOD'] == 'POST' && Eleanor::$our_query)
//						SaveAdver((int)$id);
//					else
//						AddEditAdver((int)$id);
//				break;
//				case'delete':
//					DeleteAdver((int) $id);
//			}
//			else
//				AdverBeginPage();
//		break;
		case'categories':
			if (!$Eleanor->Categories->dump)
				return GoAway();
			global$title;
			$title[] = Eleanor::$Language[$Eleanor->mconfig['n']]['categs'];
			$c = Eleanor::$Template->ShowCategories(0, AdverBeginPage(0, 1));
			Start();
			echo$c;
		break;
		case'em':
			if ($Eleanor->Url->is_static)
				$id = (isset($_GET['']) and is_array($_GET[''])) ? reset($_GET['']) : false;
			else
				$id = isset($_GET['id']) ? (string) $_GET['id'] : false;
			if($_SERVER['REQUEST_METHOD'] == 'POST' and Eleanor::$our_query)
				EmailSent((int)$id);
			else
				EmailAdver((int)$id);
		break;
		default:
			if (preg_match('#^(\d{4})\D(\d{1,2})(?:\D(\d{1,2}))?$#', $d, $ma) > 0)
				AdverDate($d);
			else
				AdverBeginPage();
	}
}
elseif ($nid || $adver)
	ShowAdver($nid, $adver, $cid, $curls);
elseif ($cid || $curls)
	AdverCategory($cid, $curls);
else
	AdverBeginPage();

function cr() {
	global$Eleanor;
	$conf = include($Eleanor->module['path'].'config.php');
	$Eleanor->mconfig = include($Eleanor->module['path'] . 'config.php');
	Eleanor::$Language->Load($Eleanor->module['path'] . 'lang_user-*.php', $Eleanor->mconfig['n']);
	#if(Eleanor::$Cache->Get($conf['n'].'-runned')===false)
	{
		Eleanor::$Cache->Put($conf['n'].'-runned',true,100);

		$time = strtotime("+2 day");
		$dateend = date("Y-m-d H:i:s", $time);

		$R = Eleanor::$Db->Query('SELECT `email`,`title`,`text` FROM `'.$conf['t'].'` INNER JOIN `'.$conf['tl'].'` USING (`id`) WHERE `status`=1 AND `date_end`<=\''.$dateend.'\'');

		if (Eleanor::$Db->NumRows($R)>0) {
			$lang = Eleanor::$Language[$GLOBALS['Eleanor']->mconfig['n']];
			$Email=new Email;

			while($arr=$R->fetch_assoc())
			{

				$Email->parts=array(
					'multipart' => 'mixed',
					array(
						'content-type' => 'text/html',
						'charset' => DISPLAY_CHARSET,
						'content' => $lang['end2'] . '<br><br>' . $arr['text'],
					),
				);

				$Email->subject = 'Auto '.$arr['title'];
				$Email->from = 'info-no-reply@autodiagnostika.lv';
				#$Email->notice=0;
				$Email->notice_on = false;
				$Email->Send(array('to'=>$arr['email']));
			}
		}
	}
}

function AdverBeginPage($s = false, $return = false) {
	global$Eleanor, $title;
	$title[] = Eleanor::$Language[$Eleanor->mconfig['n']]['adver'];
	$qu = '';
	if (!$s)
		$qu = 'ORDER BY `ldate` DESC';
	else
		$qu=$s;
	$R = Eleanor::$Db->Query('SELECT COUNT(*) FROM `' . $Eleanor->mconfig['t'] . '` WHERE `status` = 1');
	list($cnt) = $R->fetch_row();

	$np = $cnt % Eleanor::$vars['publ_per_page'];
	$pages = max(ceil($cnt / Eleanor::$vars['publ_per_page']) - ($np > 0 ? 1 : 0), 1);

	$page = isset($_GET['page']) ? (int) $_GET['page'] : $pages;
	$intpage = $pages - $page + 1;
	$offset = max(0, $intpage - 1) * Eleanor::$vars['publ_per_page'];

	$limit = Eleanor::$vars['publ_per_page'];
	if ($offset == 0)
		$limit += $np;
	else
		$offset += $np;

	if ($cnt and $offset >= $cnt)
	$offset = max(0, $cnt - $limit);

	$r = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`reads`,`author`,`author_id`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod`,`price`,`ldate` FROM `' . $Eleanor->mconfig['t'] . '` INNER JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `language`IN(\'\',\'' . Language::$main . '\') AND `lstatus`=1 '.$qu.' LIMIT ' . $offset . ', ' . $limit);
	$d = AdverList($r, empty($Eleanor->module['general']));

	if (!$d)
		return;
    SetData();
	if ($return)
		return $d;
	$links=array(
		'first_page'=>$Eleanor->Url->Prefix(false),
		'pages'=>function($n){ return$GLOBALS['Eleanor']->Url->Construct(array(array('page'=>$n))); },
	);

	$c = Eleanor::$Template->AdverList($d, $cnt - $np, -$page, $pages, Eleanor::$vars['publ_per_page'], $links);
	$c .= AddEditAdver(0, 0, 1);
	$Eleanor->origurl = PROTOCOL . Eleanor::$punycode . Eleanor::$site_path . $Eleanor->Url->Construct(array('page' => array('page' => $page == $pages ? false : $page)));
	Start();
	echo$c;
}

function AdverList($r, $caching = true, $anurl=array()) {
	global$Eleanor;
	$items = $ucats = $rating = array();
	$lmod = 0;
	$ids = ',';
	while ($arr = $r->fetch_assoc()) {
		$ids.=$arr['id'] . ',';
		if ($arr['last_mod'] > $lmod)
		$lmod = $arr['last_mod'];

		$arr['_cat'] = $arr['cats'] ? (int)ltrim($arr['cats'], ',') : false;
		if ($arr['_cat'])
		$ucats[$arr['_cat']] = $Eleanor->Categories->GetUri($arr['_cat']);


		OwnBB::$opts['alt'] = $arr['title'];
		$arr['text'] = OwnBB::Parse($arr['text']);

		$u = array('u' => array($arr['uri'], 'nid' => $arr['id'])) + $anurl;
		$arr['_url'] = $Eleanor->Url->Construct(($arr['_cat'] && $Eleanor->Url->furl && isset($ucats[$arr['_cat']])) ? $ucats[$arr['_cat']] + $u : $u);
		if ($R = Eleanor::$Db->Query('SELECT `path` FROM `'. $Eleanor->mconfig['i'] .'` WHERE `adver_id` = "'. $arr['id'] .'" ORDER BY `id` LIMIT 1')) {
			$a = $R->fetch_row();
			$arr['image'] = $a[0];
		}
		$items[] = $arr;
	}

	$uid = Eleanor::$Login->GetUserValue('id');
	if ($caching and Eleanor::$caching) {
		Eleanor::$last_mod = $lmod;
		$etag = Eleanor::$etag;
		Eleanor::$etag = md5($uid . $ids . $Eleanor->mconfig['n']);
		if (Eleanor::$modified && Eleanor::$last_mod && Eleanor::$last_mod <= Eleanor::$modified && $etag && $etag == Eleanor::$etag)
			return Start();
		else
			Eleanor::$modified = false;
	}

	foreach ($ucats as &$v)
		$v = $Eleanor->Url->Construct($v, true, $Eleanor->Url->delimiter);
	return compact('items', 'ucats');
}

function AdverCategory($cid, $curls) {
	global$Eleanor, $title;
	$category = $Eleanor->Categories->GetCategory($cid ? $cid : $curls);
	if (!$category)
		return ExitPage();

	if ($category['meta_title'])
		$title = $category['meta_title'];
	else
		$title[] = $category['title'];

	if ($category['meta_descr'])
		$Eleanor->module['description'] = $category['meta_descr'];

	if (Eleanor::$vars['publ_catsubcat']) {
		$carr = array($category['id']);
		$p = $category['parents'] . $category['id'] . ',';
		foreach ($Eleanor->Categories->dump as $k => &$v)
		if (strpos($v['parents'], $p) === 0)
		$carr[] = $k;
		$cwhere = count($carr) > 1 ? 'REGEXP (\',(' . join('|', $carr) . '),\')' : 'LIKE \'%,' . $category['id'] . ',%\'';
	}
	else
		$cwhere = 'LIKE \'%,' . $category['id'] . ',%\'';

	$R = Eleanor::$Db->Query('SELECT COUNT(`lstatus`) FROM `' . $Eleanor->mconfig['tl'] . '` WHERE `language`IN(\'\',\'' . Language::$main . '\') AND `lstatus`=1 AND `lcats` ' . $cwhere . '');
	list($cnt) = $R->fetch_row();

	$np = $cnt % Eleanor::$vars['publ_per_page'];
	$pages = max(ceil($cnt / Eleanor::$vars['publ_per_page']) - ($np > 0 ? 1 : 0), 1);
	$page = isset($_GET['page']) ? (int) $_GET['page'] : $pages;
	$intpage = $pages - $page + 1;
	$offset = max(0, $intpage - 1) * Eleanor::$vars['publ_per_page'];

	$limit = Eleanor::$vars['publ_per_page'];
	if ($offset == 0)
		$limit += $np;
	else
		$offset += $np;

	if ($cnt and $offset >= $cnt)
	$offset = max(0, $cnt - $limit);
	$r = Eleanor::$Db->Query('SELECT `id`,`cats`,`date`,`author`,`author_id`,`show_detail`,`reads`,`uri`,`price`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `' . $Eleanor->mconfig['t'] . '` INNER JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `language`IN(\'\',\'' . Language::$main . '\') AND `lstatus`=1 AND `lcats` ' . $cwhere . ' ORDER BY `ldate` DESC LIMIT ' . $offset . ', ' . $limit);
	$d = AdverList($r);

	if (!$d)
		return;
	$links = array(
		'first_page' => $Eleanor->Url->Prefix(false),
		'pages' => function($n){ return$GLOBALS['Eleanor']->Url->Construct(array(array('page' => $n))); },
	);

	$c = Eleanor::$Template->AdverCategoryList($category, $d, $cnt, -$page, $pages, Eleanor::$vars['publ_per_page'], $links);
	$c .= AddEditAdver(0, 0, 1);

	$Eleanor->origurl = PROTOCOL . Eleanor::$punycode . Eleanor::$site_path . $Eleanor->Url->Construct($Eleanor->Categories->GetUri($category['id']) + array('page' => array('page' => $page == $pages ? false : $page)), true, $Eleanor->Url->delimiter);
	Start();
	echo$c;
}

function AdverDate($d) {
	global$Eleanor, $title;
	if (strtotime($d) > time())
	return GoAway(true);
	$title[] = sprintf(Eleanor::$Language[$Eleanor->mconfig['n']]['adver_for'], Eleanor::$Language->Date($d, strlen($d) > 7 ? 'fd' : 'my', array('lowercase' => true)));
	$R = Eleanor::$Db->Query('SELECT COUNT(`lstatus`) FROM `' . $Eleanor->mconfig['t'] . '` INNER JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `language`IN(\'\',\'' . Language::$main . '\') AND `lstatus`=1 AND IF(`pinned` IS NULL,`date`,`pinned`) LIKE \'' . $d . '%\'');
	list($cnt) = Eleanor::$Db->FetchRow();

	$np = $cnt % Eleanor::$vars['publ_per_page'];
	$pages = max(ceil($cnt / Eleanor::$vars['publ_per_page']) - ($np > 0 ? 1 : 0), 1);
	$page = isset($_GET['page']) ? (int) $_GET['page'] : $pages;
	$intpage = $pages - $page + 1;
	$offset = max(0, $intpage - 1) * Eleanor::$vars['publ_per_page'];

	$limit = Eleanor::$vars['publ_per_page'];
	if ($offset == 0)
	$limit+=$np;
	else
	$offset+=$np;

	if ($cnt and $offset >= $cnt)
	$offset = max(0, $cnt - $limit);
	$r = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`reads`,`comments`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `' . $Eleanor->mconfig['t'] . '` INNER JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `language`IN(\'\',\'' . Language::$main . '\') AND `lstatus`=1 AND IF(`pinned` IS NULL,`date`,`pinned`) LIKE \'' . $d . '%\' ORDER BY `ldate` DESC LIMIT ' . $offset . ', ' . $limit);
	$data = AdverList($r);
	if (!$data)
	return;
	$c = Eleanor::$Template->AdverDateList($d, $data, $cnt - $np, $page, Eleanor::$vars['publ_per_page']);
	$Eleanor->origurl = PROTOCOL . Eleanor::$punycode . Eleanor::$site_path . $Eleanor->Url->Construct(array('do' => $d), true, '');
	Start();
	echo$c;
}

function MyAdver() {
	global$Eleanor, $title;
	$title[] = Eleanor::$Language[$Eleanor->mconfig['n']]['my'];
	$uid = Eleanor::$Login->GetUserValue('id');
	$R = Eleanor::$Db->Query('SELECT COUNT(`author_id`) FROM `' . $Eleanor->mconfig['t'] . '` WHERE `author_id`=' . $uid);
	list($cnt) = $R->fetch_row();

	$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
	if ($page < 1)
	$page = 1;
	$offset = ($page - 1) * $cnt;

	if ($cnt and $offset >= $cnt)
	$offset = max(0, $cnt - Eleanor::$vars['publ_per_page']);
	$r = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`pic`,`r_total`,`reads`,`status`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `' . $Eleanor->mconfig['t'] . '` INNER JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `language`IN(\'\',\'' . Language::$main . '\') AND `author_id`=' . $uid . ' ORDER BY `ldate` DESC LIMIT ' . $offset . ', ' . Eleanor::$vars['publ_per_page']);
	$d = AdverList($r);
	if (!$d)
	return;
	$c = Eleanor::$Template->AdverAuthorList($d, $cnt, $page, Eleanor::$vars['publ_per_page']);
	Start();
	echo$c;
}

function ShowAdver($nid, $adver, $cid, $curls) {
	global$Eleanor, $title;
	$where = $nid ? '`id`=' . (int) $nid : '`uri`=\'' . Eleanor::$Db->Escape($adver, false) . '\'';
	$aid = (int) Eleanor::$Login->GetUserValue('id');
	$R = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned` IS NULL,`date`,`pinned`) `date`,`author`,`author_id`,`reads`,`status`,`uri`,`title`,`text`,`name`,`price`,`telefon`,`email`,`webadres`,`pasta_index`,`adres`,`region`,`rajon`,`meta_title`,`meta_descr`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `' . $Eleanor->mconfig['t'] . '` AS `t` INNER JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `language`IN(\'\',\'' . Language::$main . '\') AND ' . $where . ' LIMIT 1');
	if (!$arr = $R->fetch_assoc() or ($arr['status'] != 1 and (!Eleanor::$Permissions->IsAdmin() and $arr['author_id'] != $aid or $aid == 0)))
		return ExitPage();
	$arr['_cat'] = $arr['cats'] ? (int) ltrim($arr['cats'], ',') : false;
	$u = array('u' => array($arr['uri'], 'nid' => $arr['id']));
	if ($arr['_cat'] and $Eleanor->Url->furl) {
		$cu = $Eleanor->Categories->GetUri($arr['_cat']);
		if ($cu)
		$u = $cu + $u;
	}
	if ($cid or $curls or $nid and $arr['uri']) {
//		$category = $Eleanor->Categories->GetCategory($cid, $curls);
		// if ($category and $category['id'] != $arr['_cat'])
		// return GoAway($u);
	}
	$R = Eleanor::$Db->Query('SELECT `path` FROM `'. $Eleanor->mconfig['i'] .'` WHERE `adver_id` = "'. $arr['id'] .'"');

	if ($R->num_rows) {
		while($a = $R->fetch_row()) {
			$arr['images'][] = $a[0];
		}
	}

	if(!Eleanor::$is_bot and $arr['status']==1) {
		#Не будем увеличивать счетчик просмотров от переходов по страницам новости
		$ref=getenv('HTTP_REFERER');
		$uu=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct($u,true,'');
		$uu=htmlspecialchars_decode($uu,ELENT);
		if(strpos($ref,$uu)===false)
			Eleanor::$Db->Update($Eleanor->mconfig['t'], array('!reads' => '`reads` + 1'),'`id`='. $arr['id']. ' LIMIT 1');
	}

	if (Eleanor::$caching) {
		Eleanor::$last_mod = $arr['last_mod'];
		$etag = Eleanor::$etag;
		$uid = Eleanor::$Login->GetUserValue('id');
		Eleanor::$etag = md5($uid . '-' . $arr['id'] . '-' . $Eleanor->mconfig['n']);
		if (Eleanor::$modified and Eleanor::$last_mod and Eleanor::$last_mod <= Eleanor::$modified and $etag and $etag == Eleanor::$etag)
			return Start();
		else
			Eleanor::$modified = false;
	}

	if ($arr['meta_title'])
		$title = $arr['meta_title'];
	else
		$title[] = $arr['title'];

	if ($arr['meta_descr'])
		$Eleanor->module['description'] = $arr['meta_descr'];

	OwnBB::$opts['alt'] = $arr['title'];

	$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
	$Eleanor->origurl = PROTOCOL . Eleanor::$punycode . Eleanor::$site_path . $Eleanor->Url->Construct($u + array('p' => array('p' => $page > 1 ? $page : false)));

	$arr['text'] = OwnBB::Parse($arr['text']);

	$navi = $Eleanor->Categories->BreadCrumbs($arr['_cat'], $Eleanor->mconfig['c'], $Eleanor->mconfig['cl']);
	$c = Eleanor::$Template->ShowAdver($arr, $Eleanor->Categories->GetCategory($arr['_cat']), $page, $navi, $Eleanor->Comments->off ? '' : $Eleanor->Comments->Show($arr['id']));
	Start();
	echo$c;
}

function AddEditAdver($id, $error='', $only_layout = false) {
	global $Eleanor, $title;

	$values = array(
		'cats' => array(),
		'status' => 1,
		#Языковые
		'uri' => '',
		'title' => '',
		'text' => '',
		#Специальные
		'_maincat' => 0,
		'price' => 0,
		'telefon' => '',
		'email' => '',
		'name' => '',
		'city' => '',
		'pasta_index' => '',
		'adres' => '',
		'webadres' => '',
		'region' => '',
		'rajon' => '',
		'pic' => '',
	);
	$title = Eleanor::$Language[$Eleanor->mconfig['n']]['list'];
//    $lang = Eleanor::$Language[$Eleanor->mconfig['n']];
	if ($error == '' and $ch = $Eleanor->TimeCheck->Check($Eleanor->mconfig['n'] . '-add'))
	$error = sprintf(Eleanor::$Language[$Eleanor->mconfig['n']]['flood_limit'], Eleanor::$Permissions->FloodLimit(), $ch['date_ts'] - time());

	if ($error) {
		$bypost = true;
		if ($error === true)
			$error = '';

		$values['title'] = isset($_POST['title']) ? (string) $_POST['title'] : null;
		$values['text'] = isset($_POST['text']) ? (string) $_POST['text'] : null;
		$values['uri'] = isset($_POST['uri']) ? (string) $_POST['uri'] : null;
		$values['price'] = isset($_POST['price']) ? (int) $_POST['price'] : null;
		$values['_maincat'] = isset($_POST['_maincat']) ? (int) $_POST['_maincat'] : 0;
		$values['cats'] = isset($_POST['cats']) ? (array) $_POST['cats'] : array();
		$values['email'] = isset($_POST['email']) ? (string) $_POST['email'] : null;
		$values['city'] = isset($_POST['city']) ? (string) $_POST['city'] : null;
		$values['telefon'] = isset($_POST['telefon']) ? (string) $_POST['telefon'] : null;
		$values['name'] = isset($_POST['name']) ? (string) $_POST['name'] : null;
		$values['pasta_index'] = isset($_POST['pasta_index']) ? (string) $_POST['pasta_index'] : null;
		$values['adres'] = isset($_POST['adres']) ? (string) $_POST['adres'] : null;
		$values['webadres'] = isset($_POST['webadres']) ? (string) $_POST['webadres'] : null;
		$values['region'] = isset($_POST['region']) ? (string) $_POST['region'] : null;
		$values['rajon'] = isset($_POST['rajon']) ? (string) $_POST['rajon'] : null;
		$values['images'] = isset($_POST['images']) ? $_POST['images'] : null;
	}

	$c = Eleanor::$Template->AddEdit($id, $values, $error);
	if ($only_layout)
		return $c;
	Start();
	echo$c;
}


function EmailAdver($id, $error='') {
	global$Eleanor;
	if($id) {
		$v = array('ot'=>'','text'=>'');
		$R = Eleanor::$Db->Query('SELECT `title` FROM `' . $Eleanor->mconfig['tl'] . '` WHERE id=' . $id . ' LIMIT 1');
		$values=array_merge($R->fetch_assoc(), $v);

		if ($error) {
			if ($error === true)
			$error = '';

			$values['sub'] = isset($_POST['sub']) ? (string) $_POST['sub'] : null;
			$values['ot'] = isset($_POST['ot']) ? (string) $_POST['ot'] : null;
			$values['text'] = isset($_POST['text']) ? (string) $_POST['text'] : null;
		}
		$c = Eleanor::$Template->Email($id, $values, $error);
		Start();
		echo$c;
	}
}


function EmailSent($id) {
	global$Eleanor, $title;
	if($id) {
		$lang = Eleanor::$Language[$Eleanor->mconfig['n']];
		$R = Eleanor::$Db->Query('SELECT `email` FROM `' . $Eleanor->mconfig['tl'] . '` WHERE id=' . $id . ' LIMIT 1');
		$v=$R->fetch_assoc($R);

		if (!$Eleanor->Captcha->Check(isset($_POST['check']) ? (string) $_POST['check'] : null))
		return EmailAdver($id, $lang['error_captcha']);
		if(!($_POST['ot']) or $Eleanor->Strings->CheckEmail($_POST['ot'])===false)
		return EmailAdver($id,$lang['ema_empty']);
		if(empty($_POST['text']))
		return EmailAdver($id,$lang['tex_empty']);

		#$values = array('ot'=>'','text'=>'');

		$Email=new Email;
		$Email->parts=array(
			'multipart'=>'mixed',
			array(
				'content-type'=>'text/html',
				'charset'=>DISPLAY_CHARSET,
				'content'=>$_POST['text'],
			),
		);

		#$lang=Eleanor::FilterLangValues($langs,$v['language']);
		$Email->subject=$_POST['sub'];
		$Email->from=$_POST['ot'];
		#$Email->notice=0;
		#$Email->notice_on=0;

		if($Email->Send(array('to'=>$v['email'])))
		{
			$c = Eleanor::$Template->EmailC();
		}
		Start();
		echo$c;
	}
}

function SaveAdver($id) {
	global$Eleanor, $title;
	$lang = Eleanor::$Language[$Eleanor->mconfig['n']];
//	if ($id === false and $ch = $Eleanor->TimeCheck->Check($Eleanor->mconfig['n'] . '-add'))
//	return AddEditAdver($id, sprintf($lang['flood_limit'], Eleanor::$Permissions->FloodLimit(), $ch['date_ts'] - time()));

	$aid = (int) Eleanor::$Login->GetUserValue('id');
	if ($id) {
		$R = Eleanor::$Db->Query('SELECT `author_id`,`date` FROM `' . $Eleanor->mconfig['t'] . '` WHERE id=' . $id . ' LIMIT 1');
		if (!$old = $R->fetch_assoc() or !Eleanor::$Permissions->IsAdmin() and $old['author_id'] != $aid or $aid == 0)
			return GoAway(true);
	}

//	if (!$Eleanor->Captcha->Check(isset($_POST['check']) ? (string) $_POST['check'] : null))
//	return AddEditAdver($id, $lang['error_captcha']);
	if(!$_POST['telefon'])
		return AddEditAdver($id, $lang['tel_empty']);

	if(!$_POST['email'] || !$Eleanor->Strings->CheckEmail($_POST['email']))
		return AddEditAdver($id, $lang['ema_empty']);

    $goroda=array('Liepājas rajons','Rēzeknes rajons','Aizkraukles rajons','Rīgas rajons','Rīga','Aluksnes rajons','Balvu rajons','Bauskas rajons','Cēsu rajons','Daugavpils rajons','Dobeles rajons','Gulbenes rajons','Jēkabpils rajons','Jelgavas rajons','Krāslavas rajons','Kuldīgas rajons','Limbažu rajons','Ludzas rajons','Madonas rajons','Ogres rajons','Preiļu rajons','Saldus rajons','Tukuma rajons','Talsu rajons','Valkas rajons','Valmieras rajons','Ventspils rajons');
    sort($goroda);
	$mod = Eleanor::$Permissions->Moderate();
	$price = isset($_POST['price']) ? (int)$_POST['price'] : 0;
	$email = isset($_POST['email']) ? (string)$_POST['email'] : null;
	$name = isset($_POST['name']) ? (string)$_POST['name'] : null;
	$telefon = isset($_POST['telefon']) ? (string)$_POST['telefon'] : null;
	$city = isset($_POST['city']) ? (string)$_POST['city'] : null;
	$pasta_index = isset($_POST['pasta_index']) ? (string)$_POST['pasta_index'] : null;
	$adres = isset($_POST['adres']) ? (string)$_POST['adres'] : null;
	$rajon = isset($_POST['rajon']) ? (string)$_POST['rajon'] : null;
	$region = isset($_POST['region']) ? $goroda[$_POST['region']] : null;
	$webadres = isset($_POST['webadres']) ? (string)$_POST['webadres'] : null;

	$time = strtotime("+30 day");
	$dateend = date("Y-m-d H:i:s", $time);

	$maincat = isset($_POST['_maincat']) ? (int) $_POST['_maincat'] : false;
	$maincat = $maincat ? ',' .$maincat. ',' : null;

	$status = 1;
	$values = array(
		'cats' => $maincat,
		'status' => $status,
	);

	$lvalues = array(
		'title' => array('' => isset($_POST['title']) ? (string)Eleanor::$POST['title'] : null),
		'text' => array('' => $Eleanor->Editor_result->GetHtml('text')),
		'uri' => array('' => isset($_POST['uri']) ? (string) $_POST['uri'] : null),
	);

#Преобразование урл из заголовка
	foreach ($lvalues['uri'] as $k => $v) {
		if ($v)
		$v = htmlspecialchars_decode($lvalues['title'][$k], ENT_QUOTES);
		$v = $Eleanor->Url->Filter($v, $k);
		$q_and = ' AND `language`=\'' . $k . '\'' . ($id ? ' AND `id`!=' . $id : null);
		$R = Eleanor::$Db->Query('SELECT `id` FROM `' . $Eleanor->mconfig['t'] . '` INNER JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `uri`="'. $v .'"' . $q_and . ' LIMIT 1');
		if ($R->num_rows > 0) {
			$v = null;
		}
	}

	$origid = $id;
	if ($id) {
		Eleanor::$Db->Update($Eleanor->mconfig['t'], $values, 'id=' . $id . ' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->mconfig['tl'], '`id`=' . $id . ' AND `language`' . Eleanor::$Db->In($langs, true));
		$title[] = $lang['nssedit'];
	} else {
		$date = date('Y-m-d H:i:s');
		$values += array(
			'date' => $date,
			'author' => Eleanor::$Login->GetUserValue('name'),
			'author_id' => $aid,
		);

		$id = Eleanor::$Db->Insert($Eleanor->mconfig['t'], $values);

		$insert = array();
		if(isset($_POST['images']) && $_POST['images']) {
			foreach($_POST['images'] as $k => &$v) {
				$new_path = $_SERVER['DOCUMENT_ROOT'] .'/uploads/adver/'. $id .'/'. pathinfo($v, PATHINFO_BASENAME);
				if (file_exists($_SERVER['DOCUMENT_ROOT'] . $v)) {
					Files::MkDir($_SERVER['DOCUMENT_ROOT'] .'/uploads/adver/'. $id);
					rename($_SERVER['DOCUMENT_ROOT'] . $v, $new_path);
					rename(str_replace('_preview', null, $_SERVER['DOCUMENT_ROOT']. $v) , str_replace('_preview', null, $new_path));
					$insert[] = array(
						'adver_id' => $id,
						'path' => str_replace($_SERVER['DOCUMENT_ROOT'], null, $new_path)
					);
				} else {
					unset($_POST['images'][$k]);
				}
			}
			unset($v);
		}

		$values = array('id' => array(), 'language' => array(), 'uri' => array(), 'title' => array(), 'text' => array());

		$values['id'][] = $id;
		$values['last_mod'][] = date('Y-m-d H:i:s');
		$values['lstatus'][] = $status;
		$values['ldate'][] = $date;
		$values['lcats'][] = $maincat;

		$values['language'][] = '';
		$values['uri'][] = $lvalues['uri'][''];
		$values['title'][] =$lvalues['title'][''];
		$values['text'][] = $lvalues['text'][''];
		$values['price'][] = $price;
		$values['city'][] = $city;
		$values['telefon'][] = $telefon;
		$values['name'][] = $name;
		$values['email'][] = $email;

		$values['pasta_index'][] = $pasta_index;
		$values['adres'][] = $adres;
		$values['rajon'][] = $rajon;
		$values['region'][] = $region;
		$values['webadres'][] = $webadres;
		$values['date_end'][] = $dateend;

		Eleanor::$Db->Insert($Eleanor->mconfig['tl'], $values);
		Eleanor::$Db->Insert($Eleanor->mconfig['i'], $insert);

		#Eleanor::$Db->Commit();
		$title[] = $mod ? $lang['waitmod'] : $lang['nssadded'];
		if ($flood = Eleanor::$Permissions->FloodLimit())
			$Eleanor->TimeCheck->Add($Eleanor->mconfig['n'] . '-add', '', true, $flood);
	}
	Eleanor::$Cache->Lib->DeleteByTag($Eleanor->mconfig['n']);

	$u = array('u' => array(Eleanor::FilterLangValues($lvalues['uri']), 'nid' => $id));
	if ($maincat and $Eleanor->Url->furl) {
		$cu = $Eleanor->Categories->GetUri($maincat);
		if ($cu)
			$u = $cu + $u;
	}
	Eleanor::$Cache->Delete($Eleanor->mconfig['n'] . '_nextrun');
	$c = Eleanor::$Template->AddEditComplete(empty($_POST['back']) ? '' : $_POST['back'], $u, $origid, $status, Eleanor::FilterLangValues($lvalues['title']), $mod);
	Start();
	echo$c;
}

function DeleteAdver($id) {
	global$Eleanor, $title;
	if (!Eleanor::$our_query)
	return GoAway();
	$aid = (int) Eleanor::$Login->GetUserValue('id');
	$R = Eleanor::$Db->Query('SELECT `id`,`title`,`author_id` FROM `' . $Eleanor->mconfig['t'] . '` LEFT JOIN `' . $Eleanor->mconfig['tl'] . '` USING(`id`) WHERE `id`=' . $id . ' AND `language` IN (\'\',\'' . Language::$main . '\') LIMIT 1');
	if (!$arr = $R->fetch_assoc() or !Eleanor::$Permissions->IsAdmin() and $arr['author_id'] != $aid or $aid == 0)
		return GoAway(true);
	if (isset($_POST['ok']) and $_POST['ok'] == 'ok') {
		Files::Delete(Eleanor::$root . Eleanor::$uploads . DIRECTORY_SEPARATOR . $Eleanor->mconfig['n'] . DIRECTORY_SEPARATOR . $id);
		#$Eleanor->Comments->DeleteComments($_POST['mass']); #ToDo!
		Eleanor::$Db->Delete($Eleanor->mconfig['t'], '`id`=' . $id . ' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->mconfig['tl'], '`id`=' . $id);
		Eleanor::$Cache->Lib->DeleteByTag($Eleanor->mconfig['n']);

		$title[] = Eleanor::$Language[$Eleanor->mconfig['n']]['deleted'];
		$c = Eleanor::$Template->AdverDelSuccess($arr, empty($_POST['back']) ? false : $_POST['back']);
		Start();
		echo$c;
	} else {
		$title[] = Eleanor::$Language[$Eleanor->mconfig['n']]['del_confirm'];
		if (isset($_GET['noback']))
		$back = '';
			else
		$back = isset($_POST['back']) ? (string) $_POST['back'] : getenv('HTTP_REFERER');
		$c = Eleanor::$Template->DeleteAdver($arr, $back);
		Start();
		echo$c;
	}
}

function SetData($tpl=false)
{global$Eleanor,$head;
    $lang=Eleanor::$Language[$Eleanor->mconfig['n']];
    $Lst=Eleanor::LoadListTemplate('headfoot');
    $u='?'.Url::Query(Eleanor::$vars['multilang'] && Language::$main!=LANGUAGE ? array('lang'=>Eleanor::$langs[Language::$main]['uri'],'module'=>$Eleanor->module['name']) : array('module'=>$Eleanor->module['name']));
    $Eleanor->module['rss']=Eleanor::$services['rss']['file'].$u;
    $head['rss']=$Lst('link',array(
            'rel'=>'alternate',
            'type'=>'application/rss+xml',
            'href'=>$Eleanor->module['rss'],
            'title'=>$lang['n'],
        ));
    $head['search']=$Lst('link',array(
            'rel'=>'search',
            'type'=>'application/opensearchdescription+xml',
            'title'=>$lang['n'],
            'href'=>Eleanor::$services['xml']['file'].$u,
        ));

//    Eleanor::$Template->queue[]=$tpl ? $tpl : $Eleanor->module['config']['usertpl'];

    $tags=Eleanor::$Cache->Get($Eleanor->module['config']['n'].'_tags_'.Language::$main);
    #Cron
    if(isset(Eleanor::$services['cron']))
    {
        $cron=Eleanor::$Cache->Get($Eleanor->module['config']['n'].'_nextrun');
        $t=time();
        $cron=$cron===false && $cron<=$t ? Eleanor::$services['cron']['file'].'?'.Url::Query(array('module'=>$Eleanor->module['name'],'language'=>Language::$main==LANGUAGE ? false : Language::$main,'rand'=>$t)) : '';
    }
    else
        $cron=false;

    $Eleanor->module+=array(
        'tags'=>$tags ? $tags : null,
        'cron'=>$cron,
        'links'=>array(
            'base'=>$Eleanor->Url->Prefix(false),
            'categories'=>$Eleanor->Categories->dump ? $Eleanor->Url->Construct(array('do'=>'categories'),true,'') : false,
            'tags'=>$tags ? $Eleanor->Url->Construct(array('do'=>'tags'),true,'') : false,
            'search'=>$Eleanor->Url->Construct(array('do'=>'search'),true,''),
            'add'=>Eleanor::$vars['publ_add'] ? $Eleanor->Url->Construct(array('do'=>'add'),true,'') : false,
            'my'=>Eleanor::$vars['publ_add'] ? $Eleanor->Url->Construct(array('do'=>'my'),true,'') : false,
        )
    );
}